package com.zx.练习题._2020面试题;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CP1 {

    //1、求两个数组的交集，两个数组是顺序递增的，求交集，结果是数组
    public static void main(String[] args) {
        int[] arr1 = {2, 3, 4, 8, 9};
        int[] arr2 = {1, 2, 5, 6, 7, 9};

        int len1 = arr1.length;
        int len2 = arr2.length;

        List<Integer> resList = new ArrayList<>(len1 < len2 ? len1 : len2);

        // 使用双指针移动
        int p1 = 0, p2 = 0;

        while (p1 < arr1.length && p2 < arr2.length) {
            int a1 = arr1[p1];
            int a2 = arr2[p2];
            if (a1 == a2) {
                resList.add(a1);
                p1++;
                p2++;
            } else if (a1 < a2) {
                p1++;
            } else {
                p2++;
            }
        }

        int[] resArr = new int[resList.size()];
        for (int i = 0; i < resArr.length; i++) {
            resArr[i] = resList.get(i);
        }

        System.out.println(Arrays.toString(resArr));
    }
}
